<template>
  <div class="dynamic-list" :style="'width:'+ width+'px'"  @scroll="handleScroll">

    <div class="dynamic-list-item" v-for="(item,index) in dynamicList" :key="item.dynamicId">
      <div class="my-card">
        <div class="item-box">
          <div class="item-left">
            <a :href="'/space/home/'+item.publisherId" target="_blank">
              <el-avatar class="pointer-show" :src="item.publisherAvatar" :size="50"></el-avatar>
            </a>
          </div>
          <div class="item-right">
            <a :href="'/space/home/'+item.publisherId" target="_blank">
              <div class="up-nickname">{{ item.publisherName }}</div>
            </a>
            <div class="publish-time">
              {{ item.createTime }}
            </div>
            <div class="publish-content" v-if="item.forwardType === 0">
              <div class="publish-content-title">
                {{item.contentTitle}}
              </div>
              <div class="publish-content-text">
                {{item.contentText}}
              </div>
              <template v-if="item.contentImg instanceof Array">
                <img class="content-pic" v-for="(itemImg,index) in item.contentImg" :key="index" :src="itemImg" alt="" width="200">
              </template>
              <template v-else>
                <img class="content-pic" :src="item.contentImg" alt="" width="150">
              </template>
            </div>
            <div class="publish-content" v-else-if="item.forwardType === 2">
              <div class="publish-content-text">
                {{item.contentText}}
              </div>
              <div class="forward-box">
                <div class="forward-header">
                  <el-avatar :src="item.forwardDynamicVO.userAvatar" :size="25"></el-avatar>
                  &nbsp;
                  <span class="source-nickname">
                        {{item.forwardDynamicVO.nickname}}
                      </span>
                </div>
                <div class="forward-content">
                  <div class="publish-content-text">
                    {{item.forwardDynamicVO.contentText}}
                  </div>
                  <template v-if="item.forwardDynamicVO.contentImg instanceof Array">
                    <img class="content-pic" v-for="(itemImg,index) in item.forwardDynamicVO.contentImg" :key="index" :src="itemImg" alt="" width="200">
                  </template>
                  <template v-else>
                    <img class="content-pic" :src="item.forwardDynamicVO.contentImg" alt="" width="150">
                  </template>
                </div>

              </div>
            </div>
            <div class="publish-content" v-else-if="item.forwardType === 1">
              <div class="publish-content-text">
                {{item.contentText}}
              </div>
              <div class="forward-box">
                <!--                    <div class="forward-header">-->
                <!--                      <el-avatar :src="item.forwardVideoVO.userAvatar" :size="25"></el-avatar>-->
                <!--                      &nbsp;-->
                <!--                      <span class="source-nickname">-->
                <!--                        {{item.forwardVideoVO.nickname}}-->
                <!--                      </span>-->
                <!--                    </div>-->
                <div class="forward-content">
                  <div class="share-box">
                    <div class="share-header">
                      <a :href="'/space/home/'+item.forwardVideoVO.userId" target="_blank">
                        <el-avatar :src="item.forwardVideoVO.userAvatar" :size="30"></el-avatar>
                      </a>
                      &nbsp;
                      <a :href="'/space/home/'+item.forwardVideoVO.userId" target="_blank">
                        <span class="nickname">{{item.forwardVideoVO.nickname}}</span></a>&nbsp;
                      的投稿视频
                    </div>
                    <div class="share-content">
                      <div class="content-left">
                        <a :href="'/video?videoId='+item.forwardVideoVO.videoId" target="_blank">
                          <el-image :src="item.forwardVideoVO.videoCover" style="width: 260px;height: 150px;overflow: hidden;border-radius: 5px;" fit="cover"></el-image>
                        </a>
                      </div>
                      <div class="content-right">
                        <div>
                          <a :href="'/video?videoId='+item.forwardVideoVO.videoId" target="_blank">
                            {{item.forwardVideoVO.videoTitle}}
                          </a>
                        </div>
                        <div>
                          <a :href="'/video?videoId='+item.forwardVideoVO.videoId" target="_blank">
                            {{item.forwardVideoVO.videoIntroduction}}
                          </a>
                        </div>
                        <div class="bottom-info">
                          <el-icon><VideoPlay /></el-icon> &nbsp;{{item.forwardVideoVO.playCount}} &nbsp;&nbsp;
                          <el-icon><ChatLineSquare /></el-icon>&nbsp;{{item.forwardVideoVO.videoBarrageCount}}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="item-action">
          <div class="action-item" >
            <el-icon @click="forward(index)"><Share /></el-icon>
            {{item.forwardCount === 0 ? '转发': item.forwardCount }}
          </div>
          <div class="action-item" @click="item.showComment = !item.showComment">
            <el-icon><ChatRound /></el-icon>
            {{item.commentCount === 0 ? '评论': item.commentCount }}
          </div>
          <div class="action-item">
            <Icon icon="solar:like-broken" width="20" height="20" />
            {{item.likeCount === 0 ? '点赞': item.likeCount }}
          </div>
        </div>
        <div class="item-forward" v-if="showForward && curForward === index">
          <div class="forward-left">
            <el-avatar :src="'/img/avatar.webp'" :size="30"></el-avatar>
          </div>
          <div class="forward-right">
            <el-input
                v-model="forwardForm.forwardDesc"
                style="width: 650px"
                :rows="2"
                type="textarea"
                placeholder="请自觉遵守互联网相关的政策法规，严禁发布色情，暴力，反动的言论。"
            />
            <el-button style="width: 50px" @click="handleForward(
                    item.forwardType === 0?item.dynamicId:item.forwardType === 1?
                    item.forwardVideoVO.videoId:item.forwardDynamicVO.dynamicId
                )" type="primary">转发</el-button>
          </div>
        </div>
        <comment-list v-if="item.showComment" :dynamic-id="item.dynamicId"></comment-list>
      </div>

    </div>
    <el-empty v-if="isEmpty" description="没有更多动态了" />
  </div>
</template>
<script setup>
import {Icon} from "@iconify/vue";
import CommentList from "@/components/CommentList.vue";
import {onMounted, reactive, ref} from "vue";
import {forwardDynamic, getDynamicList} from "@/api/api.js";
import {useRoute, useRouter} from "vue-router";
import {useUserStore} from "@/stores/userInfoStore.js";
const prop = defineProps(["width"])
console.log(prop)

const dynamicList = ref([])
const params = reactive({
  page: 1,
  pageSize: 5,
})

const route = useRoute()
let currentUserId = 0
onMounted(async () => {
  if(route.params.userId){
    currentUserId = route.params.userId
  }else {
    currentUserId = useUserStore().userInfo.userId
  }
  if(!currentUserId){
    currentUserId = localStorage.getItem("userId")
  }

  await showDynamicList(currentUserId)
})
const router = useRouter()
// const toSpace = (id) => {
//   router.push({
//     // path:"/space/home",
//     name:'home',
//     params:{
//       id
//     }
//   })
// }

const isLoading = ref(false) // 是否正在加载
const hasMore = ref(true)// 是否还有更多数据

const showDynamicList = async (userId) => {
  console.log(userId+"被选中了")
  dynamicList.value = []
  currentSelectedUserId.value = userId
  hasMore.value = true

  params.page = 1
  await loadMore()
}

const currentSelectedUserId = ref()
const replace = ref(true)
const isEmpty = ref(false)
const loadMore = async () => {

  isEmpty.value = false
  if(isLoading.value || !hasMore.value) return;
  isLoading.value = true

  try {

    if(currentSelectedUserId.value){
      params["userId"] = currentSelectedUserId.value
    }

    // 调用 API 获取数据
    const res = await getDynamicList(params);
    console.log(res)
    console.log("剩余数据长度")
    console.log(res.data.records.length)
    if (res.data.records.length === 0) {
      hasMore.value = false; // 没有更多数据
      isEmpty.value = true
      return;
    }
    // 处理返回的图片
    res.data.records.forEach((ele)=>{
      if(ele.contentImg && ele.contentImg.includes(",")){
        const arr = ele.contentImg.split(",")
        arr.pop()
        console.log(arr)
        ele.contentImg = arr
      }
      if(ele.forwardType === 2){
        if(ele.forwardDynamicVO.contentImg && ele.forwardDynamicVO.contentImg.includes(",")){
          const arr1 = ele.forwardDynamicVO.contentImg.split(",")
          arr1.pop()
          console.log(arr1)
          ele.forwardDynamicVO.contentImg = arr1
        }
      }
      ele["showComment"] = false
    })
    if(replace.value){
      dynamicList.value = res.data.records
    }else {
      dynamicList.value = [...dynamicList.value, ...res.data.records]; // 合并新旧数据
    }
    params.page++;
  } catch (err) {
    console.error('加载失败:', err);
  } finally {
    isLoading.value = false;
  }

}





const handleScroll = (e) => {
  // console.log(e)
  // console.log(e.target)
  // params.page++
  const container = e.target;

  // 滚动到底部条件：容器高度 + 滚动距离 >= 总内容高度 - 阈值（如 100px）
  const isBottom =
      container.scrollHeight - container.scrollTop <=
      container.clientHeight + 100;

  if (isBottom && !isLoading.value && hasMore.value) {
    replace.value = false
    loadMore();
  }
}





const forwardForm = reactive({
  forwardDesc: "",
  forwardContentId: 0
})
const showForward = ref(false)
const curForward = ref(0)
const forward = (index) => {
  curForward.value = index
  showForward.value = ! showForward.value
  // handleForward(dynamicId)
}
const handleForward = async (dynamicId) => {
  console.log(dynamicId)
  forwardForm.forwardContentId = dynamicId
  const res = await forwardDynamic(forwardForm)
  console.log(res.data)
}



</script>
<style lang="scss" scoped>
.dynamic-list{
  height: 600px;
  overflow-y: auto;
  .dynamic-list-item{

    margin: 10px 0;
    .my-card{
      padding: 15px;
      border-radius: 2px;
      background-color: white;
      box-shadow: 0 0 10px 0 #bebebe;
      .item-box{
        display: flex;
        .item-left{
          width: 80px;
          padding:0 15px;
        }
        .item-right{
          .up-nickname{
            cursor: pointer;
            height: 30px;
            font-size: 19px;
            color:deeppink;
          }
          .publish-time{
            color: gray;
            font-size: 13px;
            height: 20px;
            line-height: 20px;
          }
          .publish-content{
            .content-pic{
              border-radius: 5%;
            }
            .publish-content-text{
              letter-spacing: 1px;
              margin: 10px 0;
            }
            .publish-content-title{
              letter-spacing: 1px;
              margin: 5px 0 0;
              color: #ff0089;
              font-size: 16px;
            }
            .forward-box{

              width: 680px;
              //height: 30px;
              box-sizing: border-box;
              padding: 20px;
              background-color: #eee7e7;
              border-radius: 5px;
              .forward-header{

                display: flex;
                justify-content: flex-start;
                align-items: center;
                height: 30px;
                .source-nickname{
                  color: #ff008a;
                }
              }
              .forward-content{

                color: gray;
                font-size: 13px;
                .share-box{
                  width: 650px;
                  height: 200px;
                  background-color: #e7e7e7;
                  box-sizing: border-box;
                  padding: 10px;
                  .share-header{
                    .nickname{
                      font-size: 14px;
                      color:black;
                    }
                    display: flex;align-items: center;
                    //box-sizing: border-box;
                    //padding: 5px;
                    height: 40px;
                    font-size: 12px;
                    color: gray;
                  }
                  .share-content{

                    display: flex;color: black;
                    .content-right{
                      width:490px;
                      background-color: #f5f5f5;
                      display: flex;
                      flex-direction: column;
                      justify-content: space-between;
                      box-sizing: border-box;
                      padding: 10px 20px;
                      .bottom-info{
                        display: flex;
                        align-items: center;
                        font-size: 13px;
                        color: gray;
                      }
                    }
                  }
                }
              }
            }
          }

        }
      }
      .item-action{
        margin-top: 15px;
        display: flex;
        padding-left: 80px;
        justify-content: space-between;
        .action-item{
          cursor: pointer;
        }
      }
      .item-forward{
        display: flex;
        margin-left: 80px;
        .forward-left{
          width: 40px;
          box-sizing: border-box;padding: 5px;

        }
        .forward-right{
          display: flex;
          flex-direction: column;
          align-items: flex-end;
        }
      }
    }
  }
}
</style>